﻿using System;
using System.Globalization;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace BRail.Diabolo.GuiWebApp.Common.UI
{
	/// <summary>
	/// Displays a date picker control.
	/// </summary>
	public class DatePicker : TextBox
	{
		/// <summary>
		/// Gets or sets the value of the date picker.
		/// </summary>
		/// <value>The value of the date picker.</value>
		public DateTime? Value
		{
			get
			{
				DateTime value;

				if (DateTime.TryParse(Text, out value))
					return value;

				return null;
			}
			set
			{
				Text = value.HasValue ? value.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) : "";
			}
		}


		/// <summary>
		/// Gets or sets the button image.
		/// </summary>
		/// <value>The button image.</value>
		public string ButtonImageUrl
		{
			get
			{
				string value = (string)ViewState["ButtonImageUrl"];
				if (value == null)
					value = string.Empty;
				return value;
			}
			set
			{
				ViewState["ButtonImageUrl"] = value;
			}
		}


		/// <summary>
		/// Gets or sets the disabled button image.
		/// </summary>
		/// <value>The disabled button image.</value>
		public string DisabledButtonImageUrl
		{
			get
			{
				string value = (string)ViewState["DisabledButtonImageUrl"];
				if (value == null)
					value = string.Empty;
				return value;
			}
			set
			{
				ViewState["DisabledButtonImageUrl"] = value;
			}
		}



		/// <summary>
		/// Registers client script for generating postback events prior to rendering on the client, 
		/// if <see cref="P:System.Web.UI.WebControls.TextBox.AutoPostBack"/> is true.
		/// </summary>
		/// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			if (Enabled)
			{
				// build script
				string script = RetrieveEmbeddedResource("DatePicker.js")
					.Replace("%CONTROL_ID%", ClientID)
					.Replace("%BUTTON_IMAGE_URL%", ResolveClientUrl(ButtonImageUrl));

				// register script
				Page.ClientScript.RegisterStartupScript(typeof (DatePicker),
				                                        "DatePicker" + UniqueID, script, true);
			}
		}


		/// <summary>
		/// Renders the <see cref="TextBox"/> control to the specified <see cref="HtmlTextWriter"/> object.
		/// </summary>
		/// <param name="writer">The <see cref="HtmlTextWriter"/> that receives the rendered output.</param>
		protected override void Render(HtmlTextWriter writer)
		{
			base.Render(writer);

			// emulate button when the control is disabled
			if (!Enabled)
			{
				writer.AddAttribute(HtmlTextWriterAttribute.Class, "ui-datepicker-trigger");
				writer.AddAttribute(HtmlTextWriterAttribute.Src, ResolveClientUrl(DisabledButtonImageUrl));
				writer.AddAttribute(HtmlTextWriterAttribute.Alt, "");
				writer.AddAttribute(HtmlTextWriterAttribute.Title, "");
				writer.RenderBeginTag(HtmlTextWriterTag.Img);
				writer.RenderEndTag();
			}
		}


		/// <summary>
		/// Retrieves the embedded resource with the given name.
		/// </summary>
		private static string RetrieveEmbeddedResource(string name)
		{
			using (Stream stream = typeof(DatePicker).Assembly.GetManifestResourceStream(
				typeof(DatePicker), name))
			{
				if (stream == null)
					throw new ArgumentException(
						String.Format(CultureInfo.InvariantCulture,
							"No resource with name '{0}' could be located.", name),
						"name");

				StreamReader reader = new StreamReader(stream);
				return reader.ReadToEnd();
			}
		}
	}
}
